开源 Agents - DeerFlow 源码解读
技术框架
LangGraph 是一个用于构建可控代理的底层编排框架。LangChain 提供集成和可组合组件来简化 LLM 应用程序开发,而 LangGraph 库则支持代理编排——提供可定制的架构、长期记忆和人机交互,从而可靠地处理复杂任务。

技术实现(工作流 + 智能体)
DeerFlow 技术细节可以参考该链接 langgraph-workflows-angets
核心思想: panning&solver
Prompt chaining
提示链式调用是指每个 LLM 调用都处理前一个调用的输出。它通常用于执行定义明确、可以分解为更小、可验证步骤的任务。例如:
- 将文件翻译成不同语言
- 验证生成内容的一致性

Orchestrator-Worker
在评估器-优化器工作流程中,一个 LLM 调用生成响应,另一个调用评估该响应。如果评估器或人工参与判断认为响应需要改进,则会提供反馈并重新生成响应。此循环持续进行,直至生成可接受的响应。
当任务有特定的成功标准,但需要迭代才能满足这些标准时,通常会使用评估器-优化器工作流程。例如,在两种语言之间翻译文本时,并非总能找到完美匹配的译文。可能需要多次迭代才能生成在两种语言中含义相同的译文。

代码示例
from langgraph.constants import Send
# Graph state
class State(TypedDict):
topic: str # Report topic
sections: list[Section] # List of report sections
completed_sections: Annotated[
list, operator.add
] # All workers write to this key in parallel
final_report: str # Final report
# Worker state
class WorkerState(TypedDict):
section: Section
completed_sections: Annotated[list, operator.add]
# Nodes
def orchestrator(state: State):
"""Orchestrator that generates a plan for the report"""
# Generate queries
report_sections = planner.invoke(
[
SystemMessage(content="Generate a plan for the report."),
HumanMessage(content=f"Here is the report topic: {state['topic']}"),
]
)
return {"sections": report_sections.sections}
def llm_call(state: WorkerState):
"""Worker writes a section of the report"""
# Generate section
section = llm.invoke(
[
SystemMessage(
content="Write a report section following the provided name and description. Include no preamble for each section. Use markdown formatting."
),
HumanMessage(
content=f"Here is the section name: {state['section'].name} and description: {state['section'].description}"
),
]
)
# Write the updated section to completed sections
return {"completed_sections": [section.content]}
def synthesizer(state: State):
"""Synthesize full report from sections"""
# List of completed sections
completed_sections = state["completed_sections"]
# Format completed section to str to use as context for final sections
completed_report_sections = "\n\n---\n\n".join(completed_sections)
return {"final_report": completed_report_sections}
# Conditional edge function to create llm_call workers that each write a section of the report
def assign_workers(state: State):
"""Assign a worker to each section in the plan"""
# Kick off section writing in parallel via Send() API
return [Send("llm_call", {"section": s}) for s in state["sections"]]
# Build workflow
orchestrator_worker_builder = StateGraph(State)
# Add the nodes
orchestrator_worker_builder.add_node("orchestrator", orchestrator)
orchestrator_worker_builder.add_node("llm_call", llm_call)
orchestrator_worker_builder.add_node("synthesizer", synthesizer)
# Add edges to connect nodes
orchestrator_worker_builder.add_edge(START, "orchestrator")
orchestrator_worker_builder.add_conditional_edges(
"orchestrator", assign_workers, ["llm_call"]
)
orchestrator_worker_builder.add_edge("llm_call", "synthesizer")
orchestrator_worker_builder.add_edge("synthesizer", END)
# Compile the workflow
orchestrator_worker = orchestrator_worker_builder.compile()
# Show the workflow
display(Image(orchestrator_worker.get_graph().draw_mermaid_png()))
# Invoke
state = orchestrator_worker.invoke({"topic": "Create a report on LLM scaling laws"})
from IPython.display import Markdown
Markdown(state["final_report"])StateGraph
通过 add_node 和 add_edge 构建点和边,形成图结构完成工作流的编排
DeerFlow 流程
- 接受用户问题
- 判断是否需要对用户问题进行背景信息补充,默认对背景信息进行补充
- 对用户问题进行规划分解(默认3条)
- 咨询用户是否对规划分解进行调整;(调整后重新进行第三步)
- 对子任务逐一进行联网搜索或者数据处理
- 总结任务,输出报告
"""构建并返回包含所有节点和边的基础状态图。"""
builder = StateGraph(State)
builder.add_edge(START, "coordinator")
builder.add_node("coordinator", coordinator_node)
builder.add_node("background_investigator", background_investigation_node)
builder.add_node("planner", planner_node)
builder.add_node("reporter", reporter_node)
builder.add_node("research_team", research_team_node)
builder.add_node("researcher", researcher_node)
builder.add_node("coder", coder_node)
builder.add_node("human_feedback", human_feedback_node)
builder.add_edge("reporter", END)
DeerFlow 节点说明
1. Coordinator
入口
2. Background_investigator
本质是进行整个问题进行联网信息补充

3. Planner
制定计划

'''---
CURRENT_TIME: Tue May 13 2025 10:19:43
---
You are a professional Deep Researcher. ...'''HumanMessage(content='熬夜有哪些坏处', additional_kwargs={}, response_metadata={}, id='d616864e-654b-4007-a739-b25435885ca8')'background investigation results of user query:\n[
{"title": "熬夜的危害有哪些- 热点信息 - 广西壮族自治区疾病预防控制中心", "content": "1.疲劳,精神不振,无法集中注意力,进而造成免疫力下降,感冒、肠胃道疾病、过敏等神经失调性疾病易发。 2.长期的睡眠不足导致脑细胞没有得到充分休息,人的"},
{"title": "熬夜的七大危害 - 菏泽市传染病医院", "content": "危害四,熬夜会导致人体生物钟紊乱,出现睡眠质量差,多梦易醒,神经衰弱等问题,严重的甚至会引发顽固性失眠疾病。 危害五,熬夜会提高患癌风险。长期熬夜会"},
{"title": "男性熬夜伤害更大 - 北京市人民政府", "content": "熬夜导致甲状腺激素、性激素、褪黑素分泌过低,会引起皮肤状态变差、早衰,女性还会增加卵巢囊肿、子宫肌瘤、乳腺增生等妇科疾病的风险。3.引发心血管疾病。"}
]\n'返回结果:
- 询问用户是否需要更深入的探索
- 规划的步骤

4. Human_feedback
用户反馈:补充信息+开始执行 research_team
5. Research_team
- researcher
- coder
- 异常情况重新执行 planner 阶段
6. Researcher
对 plan 进行逐一联网获取信息
- 联网搜索
- 爬虫
7. Coder
处理数据
日志: 2025-05-13 14:19:15,056 - src.graph.nodes - INFO - Research team is collaborating on tasks. 2025-05-13 14:19:15,060 - src.graph.nodes - INFO - Planner generating full plan 2025-05-13 14:21:44,137 - src.graph.nodes - INFO - Reporter write final report
8. Reporter
输出报告
[{'role': 'system', 'content': '---\nCURRENT_TIME: Tue May 13 2025 14:21:49 \n---\n\nYou are a professional reporter responsible for writing clear, comprehensive reports based ONLY on provided information and verifiable facts.\n\n# Role\n\nYou should act as an objective and analytical reporter who:\n- Presents facts accurately and impartially.\n- Organizes information logically.\n- Highlights key findings and insights.\n- Uses clear and concise language.\n- To enrich the report, includes relevant images from the previous steps.\n- Relies strictly on provided information.\n- Never fabricates or assumes information.\n- Clearly distinguishes between facts and analysis\n\n# Report Structure\n\nStructure your report in the following format:\n\n**Note: All section titles below must be translated according to the locale=zh-CN.**\n\n1. **Title**\n - Always use the first level heading for the title.\n - A concise title for the report.\n\n2. **Key Points**\n - A bulleted list of the most important findings (4-6 points).\n - Each point should be concise (1-2 sentences).\n - Focus on the most significant and actionable information.\n\n3. **Overview**\n - A brief introduction to the topic (1-2 paragraphs).\n - Provide context and significance.\n\n4. **Detailed Analysis**\n - Organize information into logical sections with clear headings.\n - Include relevant subsections as needed.\n - Present information in a structured, easy-to-follow manner.\n - Highlight unexpected or particularly noteworthy details.\n - **Including images from the previous steps in the report is very helpful.**\n\n5. **Survey Note** (for more comprehensive reports)\n - A more detailed, academic-style analysis.\n - Include comprehensive sections covering all aspects of the topic.\n - Can include comparative analysis, tables, and detailed feature breakdowns.\n - This section is optional for shorter reports.\n\n6. **Key Citations**\n - List all references at the end in link reference format.\n - Include an empty line between each citation for better readability.\n - Format: `- [Source Title](URL)`\n\n# Writing Guidelines\n\n1. Writing style:\n - Use professional tone.\n - Be concise and precise.\n - Avoid speculation.\n - Support claims with evidence.\n - Clearly state information sources.\n - Indicate if data is incomplete or unavailable.\n - Never invent or extrapolate data.\n\n2. Formatting:\n - Use proper markdown syntax.\n - Include headers for sections.\n - Prioritize using Markdown tables for data presentation and comparison.\n - **Including images from the previous steps in the report is very helpful.**\n - Use tables whenever presenting comparative data, statistics, features, or options.\n - Structure tables with clear headers and aligned columns.\n - Use links, lists, inline-code and other formatting options to make the report more readable.\n - Add emphasis for important points.\n - DO NOT include inline citations in the text.\n - Use horizontal rules (---) to separate major sections.\n - Track the sources of information but keep the main text clean and readable.\n\n# Data Integrity\n\n- Only use information explicitly provided in the input.\n- State "Information not provided" when data is missing.\n- Never create fictional examples or scenarios.\n- If data seems incomplete, acknowledge the limitations.\n- Do not make assumptions about missing information.\n\n# Table Guidelines\n\n- Use Markdown tables to present comparative data, statistics, features, or options.\n- Always include a clear header row with column names.\n- Align columns appropriately (left for text, right for numbers).\n- Keep tables concise and focused on key information.\n- Use proper Markdown table syntax:\n\n```markdown\n| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1 | Data 2 | Data 3 |\n| Data 4 | Data 5 | Data 6 |\n```\n\n- For feature comparison tables, use this format:\n\n```markdown\n| Feature/Option | Description | Pros | Cons |\n|----------------|-------------|------|------|\n| Feature 1 | Description | Pros | Cons |\n| Feature 2 | Description | Pros | Cons |\n```\n\n# Notes\n\n- If uncertain about any information, acknowledge the uncertainty.\n- Only include verifiable facts from the provided source material.\n- Place all citations in the "Key Citations" section at the end, not inline in the text.\n- For each citation, use the format: `- [Source Title](URL)`\n- Include an empty line between each citation for better readability.\n- Include images using ``. The images should be in the middle of the report, not at the end or separate section.\n- The included images should **only** be from the information gathered **from the previous steps**. **Never** include images that are not from the previous steps\n- Directly output the Markdown raw content without "```markdown" or "```".\n- Always use the language specified by the locale = **zh-CN**.'},
HumanMessage(content='# Research Requirements\n\n## Task\n\n熬夜对身体健康的影响\n\n## Description\n\n用户希望了解熬夜对身体健康的具体影响。现有信息涵盖了多个方面,包括消化系统、肝脏、心脑血管、免疫力、内分泌系统和皮肤等,但缺乏更深入的数据支持、具体案例和权威研究。因此,需要进一步收集全面且详细的信息。', additional_kwargs={}, response_metadata={}),
HumanMessage(content="IMPORTANT: Structure your report according to the format in the prompt. Remember to include:\n\n1. Key Points - A bulleted list of the most important findings\n2. Overview - A brief introduction to the topic\n3. Detailed Analysis - Organized into logical sections\n4. Survey Note (optional) - For more comprehensive reports\n5. Key Citations - List all references at the end\n\nFor citations, DO NOT include inline citations in the text. Instead, place all citations in the 'Key Citations' section at the end using the format: `- [Source Title](URL)`. Include an empty line between each citation for better readability.\n\nPRIORITIZE USING MARKDOWN TABLES for data presentation and comparison. Use tables whenever presenting comparative data, statistics, features, or options. Structure tables with clear headers and aligned columns. Example table format:\n\n| Feature | Description | Pros | Cons |\n|---------|-------------|------|------|\n| Feature 1 | Description 1 | Pros 1 | Cons 1 |\n| Feature 2 | Description 2 | Pros 2 | Cons 2 |", additional_kwargs={}, response_metadata={}, name='system'),
HumanMessage(content='Below are some observations for the research task:\n\n### 问题陈述\n熬夜对消化系统、肝脏、心脑血管、免疫系统、内分泌系统和皮肤的具体影响,包括相关疾病的发生机制、统计数据、医学研究结果和专家观点。\n\n### 研究结果\n\n#### 消化系统\n熬夜会导致消化系统功能紊乱,影响胃酸分泌和胃肠蠕动。长期熬夜可能引发胃炎、胃溃疡等疾病。熬夜还会增加胃食管反流的风险,导致消化不良和食欲下降。\n\n#### 肝脏\n熬夜会影响肝脏的解毒功能,导致毒素在体内积累。长期熬夜可能引发脂肪肝、肝炎等疾病。熬夜还会影响肝脏的代谢功能,导致血糖和血脂水平异常。\n\n#### 心脑血管\n熬夜会增加心脑血管疾病的风险,如高血压、冠心病和中风。熬夜会导致血压升高、心率加快,增加心脏负担。长期熬夜还可能引发动脉粥样硬化,增加血栓形成的风险。\n\n#### 免疫系统\n熬夜会削弱免疫系统的功能,降低身体的抵抗力。长期熬夜可能导致免疫细胞活性下降,增加感染和炎症的风险。熬夜还会影响免疫系统的调节功能,导致自身免疫性疾病的发生。\n\n#### 内分泌系统\n熬夜会扰乱内分泌系统的正常功能,导致激素分泌失衡。长期熬夜可能引发糖尿病、甲状腺功能异常等疾病。熬夜还会影响生长激素和褪黑激素的分泌,导致睡眠质量下降和生长发育迟缓。\n\n#### 皮肤\n熬夜会导致皮肤水分流失,加速皮肤老化。长期熬夜可能引发皮肤干燥、暗沉、皱纹增多等问题。熬夜还会影响皮肤的修复功能,导致皮肤屏障受损,增加痤疮和过敏的风险。\n\n### 结论\n熬夜对消化系统、肝脏、心脑血管、免疫系统、内分泌系统和皮肤均有显著的负面影响。长期熬夜可能导致多种疾病的发生,严重影响身体健康。因此,保持良好的作息习惯,避免熬夜,对于维护身体健康至关重要。\n\n### 参考文献\n- [熬夜对消化系统的影响](https://www.example.com/digestive-system)\n\n- [熬夜对肝脏的影响](https://www.example.com/liver)\n\n- [熬夜对心脑血管的影响](https://www.example.com/cardiovascular)\n\n- [熬夜对免疫系统的影响](https://www.example.com/immune-system)\n\n- [熬夜对内分泌系统的影响](https://www.example.com/endocrine-system)\n\n- [熬夜对皮肤的影响](https://www.example.com/skin)', additional_kwargs={}, response_metadata={}, name='observation'),
HumanMessage(content='Below are some observations for the research task:\n\n### 问题陈述\n\n研究熬夜对不同人群(如男性、女性、医护人员、轮班工作者等)的健康影响差异,包括性别差异、职业相关风险以及长期熬夜的累积效应。\n\n### 研究结果\n\n#### 性别差异\n1. **男性**:熬夜对男性的影响主要体现在心血管健康方面。长期熬夜可能导致血压升高、心率不齐,增加心脏病和中风的风险。此外,熬夜还会影响男性的内分泌系统,导致睾酮水平下降,影响性功能和肌肉质量。\n2. **女性**:熬夜对女性的影响更为复杂。研究表明,女性在熬夜后更容易出现情绪波动、焦虑和抑郁症状。此外,熬夜还会影响女性的月经周期,导致月经不调,甚至增加患乳腺癌的风险。\n\n#### 职业相关风险\n1. **医护人员**:医护人员由于轮班工作,常常需要熬夜。长期熬夜会导致他们出现睡眠障碍、免疫力下降,增加感染疾病的风险。此外,熬夜还会影响医护人员的认知功能,增加医疗事故的发生率。\n2. **轮班工作者**:轮班工作者,如工厂工人、司机等,由于不规律的作息时间,容易出现慢性疲劳、消化系统疾病和代谢紊乱。长期熬夜还会增加他们患糖尿病和肥胖症的风险。\n\n#### 长期熬夜的累积效应\n1. **心血管疾病**:长期熬夜会导致血压升高、心率不齐,增加心脏病和中风的风险。\n2. **代谢紊乱**:熬夜会影响人体的代谢功能,导致血糖和血脂水平异常,增加患糖尿病和肥胖症的风险。\n3. **免疫系统**:长期熬夜会削弱免疫系统,使人更容易感染病毒和细菌。\n4. **心理健康**:熬夜会导致情绪波动、焦虑和抑郁症状,长期熬夜还可能引发严重的心理疾病。\n\n### 结论\n\n熬夜对不同人群的健康影响存在显著差异。男性更容易受到心血管健康的影响,而女性则更容易出现情绪和内分泌方面的问题。医护人员和轮班工作者由于职业特性,面临更高的健康风险。长期熬夜的累积效应包括心血管疾病、代谢紊乱、免疫系统削弱和心理健康问题。因此,合理安排作息时间,减少熬夜对健康的影响至关重要。\n\n### 参考文献\n- [熬夜对男性健康的影响](https://example.com/male-health)\n\n- [熬夜对女性健康的影响](https://example.com/female-health)\n\n- [医护人员熬夜的健康风险](https://example.com/medical-staff)\n\n- [轮班工作者熬夜的健康风险](https://example.com/shift-workers)\n\n- [长期熬夜的累积效应](https://example.com/long-term-effects)', additional_kwargs={}, response_metadata={}, name='observation'),
HumanMessage(content='Below are some observations for the research task:\n\n\n\n### 问题陈述\n熬夜对健康有诸多负面影响,包括睡眠不足、免疫力下降、注意力不集中等。为了减轻熬夜的危害,我们需要了解科学的补救措施和预防建议,包括补觉技巧、饮食建议、生活习惯调整以及医学专家的具体建议。\n\n### 研究步骤\n1. **使用搜索工具**:通过搜索工具查找关于熬夜补救措施和预防建议的相关信息。\n2. **筛选信息**:从搜索结果中筛选出科学、权威的信息,包括补觉技巧、饮食建议、生活习惯调整以及医学专家的建议。\n3. **整理信息**:将筛选出的信息进行分类整理,确保信息的准确性和实用性。\n\n### 研究结果\n由于目前搜索工具无法正常工作,无法获取具体的搜索结果。建议稍后再试或使用其他可用的工具进行搜索。\n\n### 结论\n由于目前无法获取相关数据,暂时无法提供具体的补救措施和预防建议。建议稍后再试或使用其他可用的工具进行搜索。\n\n### 参考文献\n无', additional_kwargs={}, response_metadata={}, name='observation')]